/**
 * @author Peppe
 * 24/nov/2011
 */

package it.webFlora.Dao.impl;

import it.webFlora.Dao.Dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Component;

@Component
public abstract class DaoImpl<E> implements Dao<E> {

    @PersistenceContext
    protected EntityManager em;
    protected Class<E> entityClass;

    public DaoImpl() {

	ParameterizedType genericSuperclass = (ParameterizedType) getClass()
		.getGenericSuperclass();
	this.entityClass = (Class<E>) genericSuperclass
		.getActualTypeArguments()[0];
    }

    @Override
    public void insert(E entity) {
	em.persist(entity);
    }

    @Override
    public void update(E entity) {
	em.merge(entity);
    }

    @Override
    public void delete(E entity) {
	em.remove(entity);
    }

    @Override
    public List<E> findAll() {
	String unqualifiedClassName = entityClass.getName();

	String qualifiedClassName = entityClass.getName();
	if (qualifiedClassName.lastIndexOf('.') > 0) {
	    unqualifiedClassName = qualifiedClassName
		    .substring(qualifiedClassName.lastIndexOf('.') + 1);
	    // unqualifiedClassName = unqualifiedClassName.replace('$', '.'); //
	    // Map.Entry
	}

	Query q = em.createQuery("from " + unqualifiedClassName);

	return q.getResultList();
    }

    @Override
    public E findById(Integer id) {
	return em.find(entityClass, id);
    }
    @Override
    public E findByUserName(String name){
    	return em.find(entityClass, name);
    }
}
